package sources.essay;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class Station
{
    public final static int MAX_PACKET_SIZE = 65507;

    public static void main(
        String[] args )
    {
        DatagramChannel channel;
        int counter = 0;
        int port;
        String localAddress;

        try {

            channel = DatagramChannel.open();

            DatagramSocket socket = channel.socket();
            
            port = Integer.parseInt( args[2] );
            
            localAddress = args[1];

            SocketAddress address = new InetSocketAddress( port );

            try {

                socket.bind( address );

            } catch( SocketException e ) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SocketAddress socketAddress = new InetSocketAddress( localAddress, port );

            ByteBuffer buffer = ByteBuffer.allocateDirect( MAX_PACKET_SIZE );
            
            
            if (args[0].equals( "T" ))
            {
                buffer.clear();
                buffer.put( args[0].getBytes() );
                buffer.flip();
                channel.send(buffer, socketAddress);
            }

            while( counter < 10 ) {
                
                buffer.clear();
                
                SocketAddress peer = channel.receive( buffer );

                buffer.flip();
                
                String stringReceived = buildNewString( buffer, counter, args[3] );
                
                System.out.println("preparei para mandar: " + stringReceived);
                
                buffer.clear();
                
                buffer.put( stringReceived.getBytes() );
                
                buffer.flip();
                
                channel.send(buffer, peer);
                
                counter++;
                
            }

        } catch( IOException e1 ) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    public static String UnpacketString(
        CharBuffer cb )
    {
        String sReturn = "";

        if( cb.hasArray() ) {
            int limit = cb.length();
            for( int i = 0; i < limit; i++ ) {
                sReturn += String.valueOf( cb.charAt( i ) );
            }
        }

        return sReturn;
    }

    public static String buildNewString(
        ByteBuffer buffer,
        int counter, String name )
    {

        Charset charset = Charset.forName( "ISO-8859-1" );
        CharsetDecoder decoder = charset.newDecoder();

        CharBuffer out;
        try {
            out = decoder.decode( buffer );
            String outReadable = UnpacketString( out );
            
            System.out.println("Recebi: "+outReadable);
            
            return new String( String.valueOf( out.charAt( 0 ) ) + String.valueOf( counter ) + name );
        } catch( CharacterCodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "invalid";
    }
    
    public static ByteBuffer preparePacket(String string) {
      
        Charset charset = Charset.forName( "ISO-8859-1" );
        CharsetEncoder encoder = charset.newEncoder();
        try {
            return encoder.encode( CharBuffer.wrap( string ) );
        } catch( CharacterCodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        return null;
    }
}